package y_2025.m01.m02.d26;

public class ProducerConsumerDemo {
    private static final int BUFFER_SIZE = 5;
    private final int[] buffer = new int[BUFFER_SIZE];
    private int count = 0;

    // 生产者方法
    public synchronized void produce(int item) throws InterruptedException {
        // 当缓冲区满时等待
        while (count == BUFFER_SIZE) {
            wait();
        }
        System.out.println("生产者生产了: " + item);
        buffer[count++] = item;

        // 唤醒消费者
        notifyAll();
    }

    // 消费者方法
    public synchronized void consume() throws InterruptedException {
        // 当缓冲区空时等待
        while (count == 0) {
            wait();
        }
        System.out.println("消费者消费了: " + buffer[--count]);

        // 唤醒生产者
        notifyAll();
    }

    public static void main(String[] args) {
        ProducerConsumerDemo pc = new ProducerConsumerDemo();

        // 创建生产者线程
        Thread producerThread = new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    pc.produce(i);
                    Thread.sleep(1000); // 模拟生产间隔
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 创建消费者线程
        Thread consumerThread = new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    pc.consume();
                    Thread.sleep(1500); // 模拟消费间隔
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producerThread.start();
        consumerThread.start();
    }
}